const AppName = "蓝华客服平台";
const Author = "";
const Domain = "https://ser.lanhuasoft.com";
// const Domain = "https://xxdebug8100.cpolar.top";
// const MapKey = "3HQBZ-FXKCF-34QJG-JX6N4-L73OE-OJFBD";
var AppHost = "";
var UserInfo;
const ToastIcon = {
  success: "success",
  loading: "loading",
  none: "none",
};
const Service = {
  oauth: "oauth",
  share: "share",
  payment: "payment",
  push: "push",
};
export default {
  // MapKey,
  AppName,
  Author,
  Domain,
  AppHost,
  UserInfo,
  console: function (res) {
    console.log(res);
  },

  isEmptyObject: function (obj) {
    for (var key in obj) {
      return false;
    }
    return true;
  },

  parseUrl: (url, refWord) => {
    let res = {};
    let s = url.split(`${refWord}?`)[1];
    if (s == undefined) {
      return {};
    } else {
      let parms = s.split("&");
      for (let x in parms) {
        let parm = parms[x];
        res[parm.split("=")[0]] = parm.split("=")[1];
      }
      return res;
    }
  },

  navigateTo: function (link, success, fail, complete) {
    var this_ = this;
    if (this_.IsStringNull(link)) return false;
    uni.navigateTo({
      url: link,
      success: function (res) {
        if (this_.IsFunction(success)) success(res);
      },
      fail: function (res) {
        if (this_.IsFunction(fail)) fail(res);
      },
      complete: function (res) {
        if (this_.IsFunction(complete)) complete(res);
      },
    });
  },
  redirectTo: function (link, success, fail, complete) {
    var this_ = this;
    if (this_.IsStringNull(link)) return false;
    uni.redirectTo({
      url: link,
      success: function (res) {
        if (this_.IsFunction(success)) success(res);
      },
      fail: function (res) {
        if (this_.IsFunction(fail)) fail(res);
      },
      complete: function (res) {
        if (this_.IsFunction(complete)) complete(res);
      },
    });
  },
  reLaunch: function (link, success, fail, complete) {
    var this_ = this;
    if (this_.IsStringNull(link)) return false;
    uni.reLaunch({
      url: link,
      success: function (res) {
        if (this_.IsFunction(success)) success(res);
      },
      fail: function (res) {
        if (this_.IsFunction(fail)) fail(res);
      },
      complete: function (res) {
        if (this_.IsFunction(complete)) complete(res);
      },
    });
  },
  navigateBack: function (delta) {
    uni.navigateBack({
      delta: delta || 1,
    });
  },
  reload: function (link) {
    var _this = this;
    _this.redirectTo(link);
  },

  msgbox: function (msg) {
    //带确认按钮的提示框
    uni.showModal({
      content: msg,
      showCancel: false,
      success: function (res) {},
    });
  },

  // 判断是否登录
  toLogin: function () {
    uni.navigateTo({ url: "/pages/login/login" });
  },

  NativeRequest: function (
    link,
    data,
    header,
    method,
    success,
    fail,
    complete
  ) {
    var this_ = this;
    this_.console(
      "请求开始:link=" +
        link +
        ",data=" +
        JSON.stringify(data) +
        ",header=" +
        JSON.stringify(header) +
        ",method=" +
        method
    );
    uni.request({
      url: link,
      data: data || "",
      header: header || "",
      method: method,
      success: function (res) {
        if (this_.IsFunction(success) && res.statusCode == 200)
          success(res.data);
      },
      fail: function (res) {
        if (this_.IsFunction(fail)) fail(res.data || "系统错误,请稍后再试");
      },
      complete: function (res) {
        this_.console(
          "请求结束:link=" +
            link +
            ",data=" +
            JSON.stringify(data) +
            ",method=" +
            method +
            ",res=" +
            JSON.stringify(res)
        );
        if (res.errMsg == "request:fail timeout") {
          this_.msgbox("连接太久,可能服务器连接不了");
        }
        if (res.statusCode == 502) {
          this_.console("服务器无响应");
        }
        if (this_.IsFunction(fail)) {
          if (
            res.statusCode == 400 ||
            res.statusCode == 404 ||
            res.statusCode == 501
          ) {
            fail("系统错误,请稍后再试");
          }
        }
        if (this_.IsFunction(complete))
          complete(res.data || "系统错误,请稍后再试");
      },
    });
  },
  request: function (link, data, method, success, fail, complete) {
    var this_ = this;
    var header = {};
    if (this_.UserInfo && !this_.IsStringNull(this_.UserInfo.token)) {
      header.Authorization = "Bearer " + this_.UserInfo.token;
    }
    if (!this_.IsStringNull(this_.AppHost)) {
      header.redirectHost = this_.AppHost;
    }
    this_.showLoading("读取数据");
    // #ifdef APP-PLUS
    this_.NativeRequest(
      this_.AppHost + "/api/" + link,
      data,
      header,
      method,
      function (res) {
        this_.hideLoading();
        if (
          this_.IsFunction(success) &&
          !this_.IsStringNull(JSON.stringify(res)) &&
          res.code == "0"
        ) {
          success(res);
          return true;
        }
        if (this_.IsFunction(fail)) {
          fail(res);
        } else {
          this_.showToast("系统错误");
        }
      },
      function (res) {
        this_.hideLoading();
        if (this_.IsFunction(fail)) fail(res);
      },
      function (res) {
        this_.hideLoading();
        if (this_.IsFunction(complete)) complete(res);
      }
    );
    // #endif

    // #ifdef MP-WEIXIN
    this_.NativeRequest(
      this_.Domain + "/api/" + link,
      data,
      header,
      method,
      function (res) {
        this_.hideLoading();
        if (
          this_.IsFunction(success) &&
          !this_.IsStringNull(JSON.stringify(res)) &&
          res.code == "0"
        ) {
          success(res);
          return true;
        }
        if (this_.IsFunction(fail)) {
          fail(res);
        } else {
          this_.showToast("系统错误");
        }
      },
      function (res) {
        this_.hideLoading();
        if (this_.IsFunction(fail)) fail(res);
      },
      function (res) {
        this_.hideLoading();
        if (this_.IsFunction(complete)) complete(res);
      }
    );
    // #endif
  },
  getLocation: function (type, success, fail, complete) {
    var this_ = this;
    uni.getLocation({
      type: type,
      success: function (res) {
        if (this_.IsFunction(success)) success(res);
      },
      fail: function (res) {
        if (this_.IsFunction(fail)) fail(res);
      },
      complete: function (res) {
        if (this_.IsFunction(complete)) complete(res);
      },
    });
  },
  getSystemInfo: function (success) {
    var this_ = this;
    uni.getSystemInfo({
      success: function (res) {
        if (this_.IsFunction(success)) success(res);
      },
    });
  },
  vibrateShort: function (success) {
    var this_ = this;
    uni.vibrateShort({
      success: function () {
        if (this_.IsFunction(success)) success();
      },
    });
  },
  vibrateLong: function (success) {
    var this_ = this;
    uni.vibrateLong({
      success: function () {
        if (this_.IsFunction(success)) success();
      },
    });
  },
  createSelectorQuery: function (element, success) {
    var this_ = this;
    uni
      .createSelectorQuery()
      .select(element)
      .fields(
        {
          size: true,
        },
        function (res) {
          if (this_.IsFunction(success)) success(res);
        }
      )
      .exec();
  },
  createMapContext: function (amapid, element) {
    return uni.createMapContext(amapid, element);
  },
  makePhoneCall: function (phoneNumber) {
    uni.makePhoneCall({
      phoneNumber: phoneNumber,
    });
  },
  setStorage: function (key, data, success) {
    var this_ = this;
    uni.setStorage({
      key: key,
      data: data,
      success: function (res) {
        if (this_.IsFunction(success)) success(res);
      },
    });
  },
  getStorage: function (key, success, fail) {
    var this_ = this;
    uni.getStorage({
      key: key,
      success: function (res) {
        if (
          res.data != null &&
          !this_.IsStringNull(JSON.stringify(res.data)) &&
          this_.IsFunction(success)
        ) {
          success(res.data);
        } else {
          if (this_.IsFunction(fail)) fail(res);
        }
      },
      fail: function (res) {
        if (this_.IsFunction(fail)) fail(res);
      },
    });
  },
  removeStorage: function (key, success) {
    var this_ = this;
    uni.removeStorage({
      key: key,
      success: function (res) {
        if (this_.IsFunction(success)) success(res);
      },
    });
  },
  clearStorage: function (success) {
    var this_ = this;
    uni.clearStorageSync();
    if (this_.IsFunction(success)) success();
  },
  getProvider: function (service, provider, success, fail) {
    var this_ = this;
    uni.getProvider({
      service: service,
      success: function (res) {
        if (~res.provider.indexOf(provider) && this_.IsFunction(success)) {
          success(res);
        } else {
          if (this_.IsFunction(fail)) fail(res);
        }
      },
      fail: function (res) {
        if (this_.IsFunction(fail)) fail(res);
      },
    });
  },
  //字符串日期转Date类型
  StringToDate: function (dateStr, separator) {
    if (!separator) {
      separator = "-";
    }
    var dateArr = dateStr.split(separator);
    var year = parseInt(dateArr[0]);
    var month;
    if (dateArr[1].indexOf("0") == 0) {
      month = parseInt(dateArr[1].substring(1));
    } else {
      month = parseInt(dateArr[1]);
    }
    var day = parseInt(dateArr[2]);
    var date = new Date(year, month - 1, day);
    return date;
  },
  //两个日期相差的天数
  DateDiff: function (sDate1, sDate2) {
    var dateSpan = sDate2 - sDate1;
    var iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
    return iDays;
  },
  //日期转字符
  DateToString: function (date) {
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    month = month > 9 ? month : "0" + month;
    day = day > 9 ? day : "0" + day;
    return `${year}-${month}-${day}`;
  },
  //当天日期
  GetDate: function () {
    const date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    month = month > 9 ? month : "0" + month;
    day = day > 9 ? day : "0" + day;
    return `${year}-${month}-${day}`;
  },
  //本月1号
  GetFirstDayInMon: function () {
    const date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    month = month > 9 ? month : "0" + month;
    let day = "01";
    return `${year}-${month}-${day}`;
  },
  //3个月之前的日期
  GetBack3Mon: function () {
    const date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() - 8;
    if (month < 0) {
      month += 12;
      year -= 1;
    }
    month += 1;
    month = month > 9 ? month : "0" + month;
    let day = "01";
    return `${year}-${month}-${day}`;
  },
  //取前n天的日期
  dateadd: function (num) {
    var today = new Date();
    var nowTime = today.getTime();
    var ms = 24 * 3600 * 1000 * num;
    today.setTime(parseInt(nowTime + ms));
    var oYear = today.getFullYear();
    var oMoth = (today.getMonth() + 1).toString();
    if (oMoth.length <= 1) oMoth = "0" + oMoth;
    var oDay = today.getDate().toString();
    if (oDay.length <= 1) oDay = "0" + oDay;
    return `${oYear}-${oMoth}-${oDay}`;
  },
  login: function (provider, success) {
    var this_ = this;
    uni.login({
      provider: provider,
      success: function (res) {
        if (this_.IsFunction(success)) success(res);
      },
    });
  },
  getUserInfo: function (provider, success) {
    var this_ = this;
    uni.getUserInfo({
      provider: provider,
      lang: "zh_CN",
      success: function (res) {
        if (this_.IsFunction(success)) success(res);
      },
    });
  },
  requestPayment: function (res, provider, success, fail) {
    var this_ = this;
    uni.requestPayment({
      provider: provider,
      timeStamp: res.timeStamp,
      nonceStr: res.nonceStr,
      package: res.package,
      signType: res.signType,
      paySign: res.paySign,
      success: function (res) {
        if (this_.IsFunction(success)) success(res);
      },
      fail: function (res) {
        if (this_.IsFunction(fail)) fail(res);
      },
    });
  },
  scanCode: function (onlyFromCamera, success, fail) {
    var this_ = this;
    uni.scanCode({
      onlyFromCamera: onlyFromCamera,
      success: function (res) {
        if (this_.IsFunction(success)) success(res);
      },
      fail: function (res) {
        if (this_.IsFunction(fail)) fail(res);
      },
    });
  },
  chooseImage: function (count, success) {
    var this_ = this;
    uni.chooseImage({
      count: count || 9,
      success: function (res) {
        if (this_.IsFunction(success)) success(res);
      },
    });
  },
  uploadFile: function (url, file, formData, success, fail) {
    var this_ = this;
    var header = {};
    header.redirectHost = this_.AppHost;
    this_.console(
      "上传文件开始:link=" +
        url +
        ",file=" +
        file +
        ",data=" +
        JSON.stringify(formData)
    );
    this_.showLoading();
    uni.uploadFile({
      url: url,
      filePath: file,
      name: "file",
      formData: formData,
      header: header,
      success: function (res) {
        this_.hideLoading();
        if (
          this_.IsFunction(success) &&
          res.statusCode == 200 &&
          !this_.IsStringNull(JSON.stringify(res.data))
        ) {
          success(res.data);
        } else {
          if (this_.IsFunction(fail)) {
            fail(res.data);
          } else {
            this_.showToast("系统错误");
          }
        }
      },
      fail: function (res) {
        this_.hideLoading();
        if (this_.IsFunction(fail)) fail(res.data);
      },
      complete: function (res) {
        this_.console(
          "上传文件结束:link=" +
            url +
            ",file=" +
            file +
            ",data=" +
            JSON.stringify(formData) +
            ",res=" +
            JSON.stringify(res)
        );
      },
    });
  },
  downloadFile: function (url, success) {
    var this_ = this;
    uni.downloadFile({
      url: url,
      success: function (res) {
        if (res.statusCode === 200 && this_.IsFunction(success)) success(res);
      },
    });
  },
  AudioPlay: function (res, onEnded) {
    var this_ = this;
    if (this_.innerAudioContext == null) {
      this_.innerAudioContext = uni.createInnerAudioContext();
      this_.innerAudioContext.obeyMuteSwitch = false;
      this_.innerAudioContext.volume = 1;
      this_.innerAudioContext.autoplay = false;
    }
    if (this_.IsStringNull(res)) return false;

    var url =
      "https://ai.qq.com/cgi-bin/appdemo_ttsecho?text=" +
      res +
      "&speaker=7&volume=0&speed=100&format=3&aht=0&apc=58&download=1";
    this_.downloadFile(url, function (res) {
      if (this_.innerAudioContext == null) return false;
      this_.innerAudioContext.src = res.tempFilePath;
      this_.innerAudioContext.play();
      this_.innerAudioContext.onEnded(function (res) {
        if (this_.IsFunction(onEnded)) onEnded(res);
        this_.innerAudioContext.offEnded();
      });
    });
  },
  AudioStop: function () {
    var this_ = this;
    if (this_.innerAudioContext == null) return false;
    this_.innerAudioContext.stop();
    this_.innerAudioContext = null;
  },
  showToast: function (title, icon, mask, overtime) {
    var this_ = this;
    uni.showToast({
      title: title || "系统错误,请稍后再试",
      icon: icon || this_.ToastIcon.none,
      mask: true,
      duration: overtime || 2000,
    });
    setTimeout(function () {
      this_.hideToast();
    }, 2000);
  },
  hideToast: function () {
    uni.hideToast();
  },
  showLoading: function (title, mask) {
    var this_ = this;
    uni.showLoading({
      title: title || "",
      mask: true,
    });
  },
  hideLoading: function () {
    uni.hideLoading();
  },
  showModal: function (title, content, confirm, cancel, showCancel) {
    var this_ = this;
    uni.showModal({
      title: title,
      content: content,
      showCancel: showCancel,
      success: function (res) {
        if (res.confirm && this_.IsFunction(confirm)) {
          confirm(res);
        }
        if (res.cancel && this_.IsFunction(cancel)) {
          cancel(res);
        }
      },
    });
  },
  MapImage: function (res) {
    var direction = res || "";
    var image = "";
    if (direction.indexOf("调头") != -1) {
      image = "/static/image/down.png";
    } else if (direction.indexOf("左转") != -1) {
      image = "/static/image/leftzhuan.png";
    } else if (direction.indexOf("右转") != -1) {
      image = "/static/image/rightzhuan.png";
    } else {
      image = "/static/image/zhixin.png";
    }
    return image;
  },
  IsStringNull: function (res) {
    if (res == null || res == undefined) return true;
    if (
      res.toString() == "" ||
      res.toString() == " " ||
      res.toString() == "null" ||
      res.toString() == "NULL"
    )
      return true;
    if (res.toString().length == 0) return true;
    return false;
  },
  IsFunction: function (res) {
    if (res == null || res == undefined) return false;
    if (typeof res == "function") return true;
    return false;
  },
  ReplaceChar: function (res, chars) {
    var replacestr = "";
    for (var i = 0; i < res.length; i++) {
      replacestr = replacestr + "" + chars;
    }
    replacestr = replacestr.substring(0, replacestr.length - 1);
    return replacestr;
  },
  Random: function (length) {
    var num = "";
    for (var i = 0; i < length; i++) {
      num += parseInt(10 * Math.random());
    }
    return num;
  },
  ToInt: function (res) {
    return Number(res || "0");
  },
  ToBool: function (res) {
    return res == true || res == "true" || res == "True" || res == "TRUE";
  },
  ToFloat: function (res) {
    return parseFloat(res || "0");
  },
  GetArrayVal: function (res, num, key) {
    var this_ = this;
    res = this_.GetArray(res, num);
    if (!res.hasOwnProperty(key)) return "";
    return res[key];
  },
  GetArray: function (res, num) {
    if (res == null || res == undefined) return [];
    if (res[num] == null || res[num] == undefined) return [];
    return res[num] || [];
  },
  ClearTimer: function () {
    var this_ = this;
    this_.SecondNum = 60;
    clearInterval(this_.Timer);
  },
  SendCode: function (phone, run, callback, success) {
    var this_ = this;
    if (this_.SecondNum != 60) return false;
    if (this_.IsStringNull(phone) || phone.length != 11) {
      this_.showToast("请输入手机号");
      return false;
    }
    this_.SecondNum = 60;
    var outcode = this_.Random(6);
    run(outcode);
    this_.request(
      this_.Host.SendMsg,
      {
        Phone: phone,
        Msg: outcode,
      },
      "POST",
      function (res) {
        if (res == "1") {
          this_.Timer = setInterval(
            this_.CountDown,
            1000,
            this_,
            callback,
            success
          );
          this_.showToast("发送成功", this_.ToastIcon.success);
        } else {
          this_.showToast("发送失败");
        }
      },
      function (res) {
        this_.showToast("发送失败");
      }
    );
  },
  CountDown: function (this_, callback, success) {
    this_.SecondNum--;
    callback(this_.SecondNum + "秒");
    if (this_.SecondNum > 0) return false;
    this_.ClearTimer();
    success("获取验证码");
  },
  WriteFile: function (fileName, context, success, fail) {
    var _this = this;
    // #ifdef APP-PLUS
    plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function (fs) {
      fs.root.getFile(
        fileName,
        {
          create: true,
        },
        function (fileEntry) {
          fileEntry.createWriter(
            function (write) {
              write.write(context);
              if (_this.IsFunction(success)) success();
            },
            function (error) {
              if (_this.IsFunction(fail)) fail(error);
            }
          );
        }
      );
    });
    // #endif

    // #ifndef APP-PLUS
    if (_this.IsFunction(success)) success();
    //#endif
  },
  ReadFile: function (fileName, success, fail) {
    var _this = this;
    // #ifdef APP-PLUS
    plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function (fs) {
      fs.root.getFile(
        fileName,
        {
          create: true,
        },
        function (fileEntry) {
          fileEntry.file(
            function (file) {
              var fileReader = new plus.io.FileReader();
              fileReader.onloadend = function (bytes) {
                if (_this.IsFunction(success)) success(bytes.target.result);
              };
              fileReader.readAsText(file, "utf-8");
            },
            function (error) {
              if (_this.IsFunction(fail)) fail(error);
            }
          );
        }
      );
    });
    // #endif

    // #ifndef APP-PLUS
    if (_this.IsFunction(success)) success();
    //#endif
  },
  DeleteFile: function (fileName, success, fail) {
    var _this = this;
    // #ifdef APP-PLUS
    plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function (fs) {
      fs.root.getFile(
        fileName,
        {
          create: true,
        },
        function (fileEntry) {
          fileEntry.remove(
            function (res) {
              if (_this.IsFunction(success)) success(res);
            },
            function (error) {
              if (_this.IsFunction(fail)) fail(error);
            }
          );
        }
      );
    });
    // #endif

    // #ifndef APP-PLUS
    if (_this.IsFunction(success)) success();
    //#endif
  },
  install: function (tempFilePath) {
    // #ifdef APP-PLUS
    plus.runtime.install(
      tempFilePath,
      {
        force: true,
      },
      function () {
        plus.runtime.restart();
      },
      function (e) {}
    );
    // #endif
  },

  DeCodeByBase64: function (source) {
    //生成base64参照字符
    var letterLis = {};
    var s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    for (let x = 0; x < 64; x++) {
      letterLis[s.charAt(x)] = x;
    }

    var suffix_count = 0; //后缀'='的个数
    var bin6 = "";
    for (let x = 0; x < source.length; x++) {
      let ss = source.charAt(x);
      if (ss == "=") {
        suffix_count++;
      } else {
        let n = letterLis[source.charAt(x)];
        let t = n.toString(2);
        t = Array(7 - t.length).join("0") + t;
        bin6 += t;
      }
    }

    if (suffix_count == 1) {
      bin6 = bin6.substring(0, bin6.length - 2);
    } else if (suffix_count == 2) {
      bin6 = bin6.substring(0, bin6.length - 4);
    }

    var res = "";
    for (let x = 0; x < bin6.length; x += 8) {
      res += String.fromCharCode(parseInt(bin6.substring(x, x + 8), 2));
    }

    return res;
  },

  CheckForUpdate: function () {
    var _this = this;
    if (_this.IsStringNull(_this.AppHost)) return false;

    // #ifdef APP-PLUS
    if (plus.os.name.toLowerCase() != "android") return false;

    _this.request(
      _this.Host.Version,
      {
        platform: 1,
        version: plus.runtime.version,
      },
      "POST",
      function (res) {
        if (!_this.ToBool(res.data.hasVersion)) {
          _this.showToast("当前已是最新版本");
          return false;
        }
        _this.showLoading("发现新版本");

        if (_this.downtempFilePath != null) {
          _this.install(_this.downtempFilePath);
        } else {
          _this.downloadFile(res.data.versionFile, function (res) {
            _this.hideLoading();
            _this.downtempFilePath = res.tempFilePath;
            _this.install(_this.downtempFilePath);
          });
        }
      }
    );
    // #endif

    //#ifdef MP-WEIXIN
    if (wx.canIUse("getUpdateManager")) {
      var updateManager = wx.getUpdateManager();
      updateManager.onCheckForUpdate(function (res) {
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function () {
            wx.showModal({
              title: "更新提示",
              content: "新版本已经准备好,是否更新?",
              success: function (res) {
                if (res.confirm) {
                  updateManager.applyUpdate();
                }
              },
            });
          });
          updateManager.onUpdateFailed(function () {
            wx.showModal({
              title: "发现新版本",
              content: "发现新版本,请您删除当前小程序,重新打开",
            });
          });
        }
      });
    } else {
      wx.showModal({
        title: "提示",
        content: "当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试",
      });
    }
    //#endif
  },
};
